package com.xqboss.apps.listener;

import com.xqboss.apps.domain.nft.NftUsedRecord;
import com.xqboss.apps.enums.mq.AppMqDelayEnum;
import com.xqboss.apps.service.nft.NftUsedRecordService;
import com.xqboss.apps.service.user.UserAssetWrenchService;
import com.xqboss.common.core.mq.MqEnum;
import com.xqboss.common.core.mq.MqListener;
import com.xqboss.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;

/**
 * nft消耗消息监听
 */
@Component
@Slf4j
public class NftUsedListener extends MqListener {

    @Autowired
    private UserAssetWrenchService userAssetWrenchService;

    @Autowired
    private NftUsedRecordService nftUsedRecordService;

    @Override
    public MqEnum getEnum() {
        return AppMqDelayEnum.NFT_USED;
    }

    @Override
    @Transactional
    public ConsumeResult solve(MessageView message) {
        String value = StandardCharsets.UTF_8.decode(message.getBody()).toString();
        long nftNumberId = Long.parseLong(value);
        NftUsedRecord usedRecord = nftUsedRecordService.getByNftNumberId(nftNumberId);
        if (usedRecord.getIsReward() != 1) {
            // 奖励扳手
            userAssetWrenchService.rewardByUseNft(usedRecord.getUserId(), nftNumberId);
        }
        boolean result = nftUsedRecordService.isReward(nftNumberId);
        if (!result) {
            log.error("奖励状态更新失败,nftNumberId:{}", nftNumberId);
            throw new ServiceException("奖励状态更新失败");
        }
        return ConsumeResult.SUCCESS;
    }
}
